package com.clothing.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import com.alibaba.fastjson.JSONObject;

public class WeixinUtils
{
    // code 换取 session_key
    public final static String jscode_2_session = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";

    // 获取access_token的接口地址（GET） 限200（次/天）
    public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    // 发送模板消息
    public final static String send_template_message = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
    
    public static JSONObject fetchAccessToken(String appid, String appsecret)
    {
        String requestUrl = access_token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
        JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
        return jsonObject;
    }
    
    public static JSONObject jscodeToSession(String appid, String secret, String jsCode)
    {
        String requestUrl = jscode_2_session
            .replace("APPID", appid)
            .replace("SECRET", secret)
            .replace("JSCODE", jsCode);
        JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
        return jsonObject;
    }
    
    public static JSONObject httpRequest(String requestUrl,
            String requestMethod, String data)
    {
        JSONObject jsonObject = null;

        StringBuilder sb = new StringBuilder();
        sb.append("url=").append(requestUrl);
        sb.append(", requestMethod=").append(requestMethod);
        sb.append(", data=").append(data);
        // logger.info(sb.toString());

        StringBuffer buffer = new StringBuffer();
        try
        {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
            {
                httpUrlConn.connect();
            }

            // 当有数据需要提交时
            if (null != data)
            {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(data.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null)
            {
                buffer.append(str);
            }
            
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.parseObject(buffer.toString());
        }
        catch(ConnectException ce)
        {
            // logger.error(ce.toString());
        }
        catch(Exception e)
        {
            // logger.error(e.toString());
        }
        
        return jsonObject;
    }
    
    public static JSONObject sendTemplateMsg(String access_token, String data)
    {
        String requestUrl = send_template_message.replace("ACCESS_TOKEN",
                access_token);
        return httpRequest(requestUrl, "POST", data);
    }
    
    public static void main(String[] args)
    {
        System.out.println(fetchAccessToken("wx2ae456ca36f0dc60", "978ea35d6c30d9adcb9417c6edc0c84e"));
    }
}
